package org.model.common.aspect;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import java.util.Objects;

/**
 * 单条查询拦截处理.
 *
 * @author nlsm
 * @date 2023-6-8 09:37
 */
@Slf4j
@Aspect
public class SelectOneAspect {

    /**
     * 前置拦截 #{@link com.baomidou.mybatisplus.core.mapper.BaseMapper#selectOne(Wrapper)} 方法.
     *
     * @param joinPoint joinPoint
     */
    @Before(value = "execution(* com.baomidou.mybatisplus.core.mapper.BaseMapper.selectOne(..))")
    public void beforeSelectOne(final JoinPoint joinPoint) {
        // 获取所有参数
        Object[] params = joinPoint.getArgs();
        Object param = params[0];
        if (Objects.nonNull(param) && param instanceof Wrapper) {
            // 在执行前进行相应的操作
            Wrapper<?> wrapper = (Wrapper<?>) params[0];
            // 校验是否包含limit
            boolean hasLimit = StrUtil.containsIgnoreCase(wrapper.getSqlSegment(), "limit");
            if (!hasLimit) {
                // 通过wrapper对象添加限制条件
                if (wrapper instanceof AbstractWrapper) {
                    ((AbstractWrapper<?, ?, ?>) wrapper).last("LIMIT 2");
                    log.debug("对selectOne方法添加limit条件限制");
                }
            }
        }
    }

}
